package com.itheima.stargraph.config;

import com.itheima.stargraph.api.ComfyuiApi;
import com.itheima.stargraph.handler.ComfyuiMessageHandler;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.client.WebSocketClient;
import org.springframework.web.socket.client.WebSocketConnectionManager;
import org.springframework.web.socket.client.standard.StandardWebSocketClient;
import retrofit2.Retrofit;
import retrofit2.converter.jackson.JacksonConverterFactory;

import java.util.concurrent.TimeUnit;

/**
 * Comfyui配置类
 *
 * @Author mr.chen
 * @Date 2025-6-8 14:57
 */
@Configuration
public class ComfyuiConfig {

    @Value("${comfyuiHost}")
    private String comfyuiHost;


    /**
     * 声明Comfyui接口实例
     * @return
     */
    @Bean
    public ComfyuiApi comfyuiApi(){

        //开启Retrofit接口调用时拦截日志，控制台输出详细日志
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

        OkHttpClient client = new OkHttpClient
                .Builder()
                .addInterceptor(interceptor)
                .retryOnConnectionFailure(true)
                .connectTimeout(30, TimeUnit.SECONDS)
                .build();


        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(String.format("http://%s",comfyuiHost))
                .client(client)
                .addConverterFactory(JacksonConverterFactory.create())
                .build();
        return retrofit.create(ComfyuiApi.class);
    }

    /**
     * 声明Comfyui的websocket连接管理器实例
     * @param comfyuiMessageHandler
     * @return
     */
    @Bean
    public WebSocketConnectionManager webSocketConnectionManager(ComfyuiMessageHandler comfyuiMessageHandler) {

        WebSocketClient client = new StandardWebSocketClient();

        //ComfyUI的WebSocket服务端地址
        String url = String.format("ws://%s/ws?clientId=star-graph", comfyuiHost);

        WebSocketConnectionManager webSocketConnectionManager = new WebSocketConnectionManager(client, comfyuiMessageHandler,url );
        webSocketConnectionManager.setAutoStartup(true);

        return webSocketConnectionManager;
    }
}
